<template>
  <div class="page-bg">
    <div class="logo-container">
      <img src="@/assets/img/login/logo.png" class="logo" />
    </div>
    <div class="text-container">
      <h1 class="title">数字化投资系统</h1>
    </div>

    <div class="login-container">
      <div class="left-image">
        <img src="@/assets/img/login/1.png" />
      </div>

      <div class="login-box">
        <h2 class="login-title">重置密码</h2>

        <el-form ref="resetFormRef" :model="resetForm" :rules="resetRules" size="large">
          <el-form-item prop="email">
            <div class="flex-row">
              <el-input v-model="resetForm.email" placeholder="请输入邮箱" clearable />
              <el-button type="info" size="small" :disabled="countdown > 0" style="margin-left: 10px; width: 100px"
                @click="sendEmailCode">
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item prop="code">
            <div class="flex-row">
              <el-input v-model="resetForm.code" placeholder="请输入验证码" clearable />
              <el-button type="info" size="small" style="margin-left: 10px; width: 100px" @click="verifyCode">{{ '验证'
              }}</el-button>
            </div>
          </el-form-item>

          <el-form-item prop="newPassword">
            <el-input v-model="resetForm.newPassword" type="password" placeholder="请输入新密码" show-password clearable
              :disabled="code !== 1" />
          </el-form-item>

          <el-button type="primary" class="w-full" :loading="resetLoading" @click="handleReset">
            确认重置
          </el-button>
        </el-form>
      </div>

      <div class="copyright">
        <h1>版权所有：©山西汾飞信息技术有限公司,山西综改示范区太原唐槐路77号山西智创城1号基地4号楼6层641-642室</h1>
        <h1>备案号:晋ICP备10018730号-1</h1>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import { JSEncrypt } from 'jsencrypt'
const resetFormRef = ref<FormInstance>()
const resetLoading = ref(false)
const countdown = ref(0)
const router = useRouter()
// RSA公钥
const RSA_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM51dgYtMyF+tTQt80sfFOpSV27a7t9u
aUVeFrdGiVxscuizE7H8SMntYqfn9lp8a5GH5P1/GGehVjUD2gF/4kcCAwEAAQ==
-----END PUBLIC KEY-----`

// RSA加密函数
function encryptPassword(password: string): string {
  try {
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(RSA_PUBLIC_KEY)
    const encrypted = encrypt.encrypt(password)
    if (encrypted) {
      return encrypted
    } else {
      console.error('RSA加密失败')
      return password
    }
  } catch (error) {
    console.error('密码加密失败:', error)
    return password
  }
}


const resetForm = reactive({
  email: '',
  code: '',
  newPassword: ''
})

const resetRules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ]
}

async function sendEmailCode() {
  if (!resetForm.email) return ElMessage.warning('请输入邮箱')
  try {
    const res = await axios.post('http://6eab9aa1.r6.cpolar.top/auth/forgot-password', { email: resetForm.email })

    if (res.data.data.data !== null) {
      ElMessage.success('验证码已发送，请注意查收')
      countdown.value = 300
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) clearInterval(timer)
      }, 1000)
    } else {
      ElMessage.error(res.data.data.msg)
    }

    console.log(res);

  } catch (e: any) {
    console.log(e);

    ElMessage.error(e?.response?.data?.msg || '发送失败')
  }
}

const id = ref(-1)
const code = ref(666)
async function verifyCode() {
  if (!resetForm.code) return ElMessage.warning('请输入验证码')
  try {
    const res = await axios.post('http://6eab9aa1.r6.cpolar.top/auth/verify-code', { email: resetForm.email, code: resetForm.code })
    console.log(res);
    id.value = res.data.data.data
    code.value = res.data.data.code
    if (res.data.data.data !== null) { ElMessage.success('验证码验证成功') } else {
      ElMessage.error(res.data.data.msg)
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.msg || '验证码验证失败')
  }
}
async function handleReset() {
  resetLoading.value = true
  try {
    const res = await axios.patch(`http://6eab9aa1.r6.cpolar.top/system/user/${id.value}/password`, {
      newPassword: encryptPassword(resetForm.newPassword)
    })
    console.log(res);
    if (res.data.msg === 'ok') {
      ElMessage.success('密码重置成功')
      setTimeout(() => {
        router.push('/login')
      }, 2000)
    } else if (id.value === -1) {
      ElMessage.error('请先验证验证码')
    } else {
      ElMessage.error(res.data.msg || '密码重置失败')
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.msg || '验证码错误或重置失败')
  } finally {
    resetLoading.value = false
  }
}

</script>

<style scoped>
.page-bg {
  min-height: 100vh;
  background-image: url('@/assets/img/login/bg.png');
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.logo-container {
  position: absolute;
  top: 75px;
  left: 81px;
  z-index: 10;
}

.logo {
  width: 51px;
  height: 53px;
}

.text-container {
  position: absolute;
  top: 83px;
  left: 162px;
  z-index: 10;
}

.title {
  font-size: 32px;
  color: #006db8;
  font-weight: bold;
}

.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1002px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.3);
  padding: 79px 0;
}

.left-image {
  width: 374px;
  height: 352px;
  margin-left: 20px;
  margin-top: 20px;
}

.login-box {
  width: 350px;
  padding: 40px;
}

.login-title {
  font-size: 28px;
  color: #333;
  margin: 0;
}

.flex-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.captcha-image {
  height: 42px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.copyright {
  position: absolute;
  bottom: 20px;
  font-size: 12px;
  color: #333;
  text-align: center;
}

.el-button.w-full {
  width: 100%;
  background-color: #006DB8;
  border-color: #004e92;
  color: #fff;
}

.el-button.w-full:hover,
.el-button.w-full:focus {
  background-color: #003c70;
  border-color: #003c70;
}

.el-button.w-full:active {
  background-color: #002c52;
  border-color: #002c52;
}
</style>